<template>
  <div class="app-container">
    <!-- 试卷基本信息区域 -->
    <div class="paper-info">
      <h1 class="paper-title">{{ paper.paperName }}</h1>
      <div class="paper-metadata">
        <div class="metadata-item">
          <span>总分：</span>
          <span class="score-value">{{ paper.totalScore }}分</span>
        </div>
        <div class="metadata-item">
          <span>题目数：</span>
          <span>{{ paper.number || allQuestions.length }}题</span>
        </div>
        <div class="metadata-item">
          <span>考试时长：</span>
          <span>{{ paper.duration }}分钟</span>
        </div>
      </div>
      <!-- 倒计时计时器 - 居中显示 -->
      <div class="timer-container">
        <div class="timer" :class="{'timer-warning': remainingTime <= warningTime}">
          <i class="el-icon-alarm-clock"></i>
          <span class="time-text">剩余时间：{{ formatTime(remainingTime) }}</span>
        </div>
      </div>
    </div>

    <!-- 试卷内容区域 -->
    <div class="paper-content" v-loading="loading">
      <!-- 各题型分类显示 -->
      <!-- 单选题 -->
      <div v-if="singleChoiceQuestions.length > 0" class="question-section">
        <div class="section-title">{{ getSectionTitle(0) }}（共{{ singleChoiceQuestions.length }}题，共{{ singleChoiceTotal }}分）</div>
        <div v-for="(question, index) in singleChoiceQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
              <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[单选题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
            </div>
            <div class="question-text" v-html="question.questionContent"></div>
            <div class="options-container">
              <div class="option-item" v-for="(option, idx) in question.options" :key="idx">
                  <el-radio v-model="question.selectedAnswer" :label="option.optionKey">
                    <span class="option-key">{{ option.optionKey }}.</span>
                    <span class="option-content" v-html="option.optionContent"></span>
                  </el-radio>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 多选题 -->
      <div v-if="multiChoiceQuestions.length > 0" class="question-section">
        <div class="section-title">{{ getSectionTitle(1) }}（共{{ multiChoiceQuestions.length }}题，共{{ multiChoiceTotal }}分）</div>
        <div v-for="(question, index) in multiChoiceQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
              <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[多选题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
            </div>
            <div class="question-text" v-html="question.questionContent"></div>
            <div class="options-container">
                <el-checkbox-group v-model="question.selectedAnswers">
                <div class="option-item" v-for="(option, idx) in question.options" :key="idx">
                    <el-checkbox :label="option.optionKey">
                      <span class="option-key">{{ option.optionKey }}.</span>
                      <span class="option-content" v-html="option.optionContent"></span>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>

      <!-- 判断题 -->
      <div v-if="judgmentQuestions.length > 0" class="question-section">
        <div class="section-title">{{ getSectionTitle(2) }}（共{{ judgmentQuestions.length }}题，共{{ judgmentTotal }}分）</div>
        <div v-for="(question, index) in judgmentQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
            <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[判断题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
          </div>
            <div class="question-text" v-html="question.questionContent"></div>
          <div class="options-container">
              <div class="option-item">
                <el-radio v-model="answers[question.questionId]" label="A">
                  <div class="option-label-content">
                    <span class="option-key">A.</span>
                <span class="option-content">正确</span>
                  </div>
              </el-radio>
              </div>
              <div class="option-item">
                <el-radio v-model="answers[question.questionId]" label="B">
                  <div class="option-label-content">
                    <span class="option-key">B.</span>
                <span class="option-content">错误</span>
                  </div>
              </el-radio>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 填空题 -->
      <div v-if="fillBlankQuestions.length > 0" class="question-section">
        <div class="section-title">{{ getSectionTitle(3) }}（共{{ fillBlankQuestions.length }}题，共{{ fillBlankTotal }}分）</div>
        <div v-for="(question, index) in fillBlankQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
            <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[填空题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
            </div>
            <div class="question-text" v-html="processBlankQuestion(question.questionContent, question.questionId)"></div>
          </div>
        </div>
      </div>

      <!-- 简答题 -->
      <div v-if="essayQuestions.length > 0" class="question-section">
        <div class="section-title">{{ getSectionTitle(4) }}（共{{ essayQuestions.length }}题，共{{ essayTotal }}分）</div>
        <div v-for="(question, index) in essayQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
            <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[简答题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
          </div>
            <div class="question-text" v-html="question.questionContent"></div>
          <div class="essay-answer">
            <QuillEditor
              v-model:content="answers[question.questionId]"
              content-type="html"
              theme="snow"
              toolbar="full"
              :options="editorOptions"
            />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作区域 -->
    <div class="paper-footer">
      <el-button type="primary" @click="submitTest" :loading="submitting">交卷</el-button>
    </div>

    <!-- 提交确认对话框 -->
    <el-dialog
      title="确认交卷"
      v-model="submitDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <span>确定要交卷吗？交卷后将无法继续修改，系统将自动批改您的答案。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmSubmit" :loading="submitting">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自动提交提示对话框 -->
    <el-dialog
      title="考试时间结束"
      v-model="autoSubmitDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <span>考试时间已结束，系统将自动批改您的答卷。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirmAutoSubmit" :loading="submitting">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成绩结果对话框 -->
    <el-dialog
      title="模拟测试结果"
      v-model="resultDialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="result-summary">
        <h3>模拟测试成绩</h3>
        <div class="result-meta">
          <div class="meta-item">
            <span class="meta-label">总分：</span>
            <span class="meta-value">{{ formatDisplayScore(totalScore, paper.totalScore) }}</span>
          </div>
          <div class="meta-item">
            <span>题目总数：</span>
            <span>{{ questions.length }}题</span>
          </div>
        </div>
      </div>
      
      <div class="question-results">
        <!-- 单选题结果 -->
        <div v-if="singleChoiceQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getSectionTitle(0) }}（共{{ singleChoiceQuestions.length }}题，共{{ singleChoiceTotal }}分）</div>
          <div v-for="(question, index) in singleChoiceQuestions" :key="question.questionId" 
               class="question-item" :class="{'error-question': !question.isCorrect}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[单选题]</span>
                <span class="question-score">({{ question.questionScore }}分)</span>
              </div>
              <div class="question-text" v-html="question.questionContent"></div>
              <div class="options-container">
                <div class="option-item" v-for="(option, idx) in question.options" :key="idx">
                  <el-radio v-model="question.selectedAnswer" :label="option.optionKey" disabled>
                    <div class="option-label-content">
                      <span class="option-key">{{ option.optionKey }}.</span>
                      <span class="option-content" v-html="option.optionContent"></span>
                    </div>
                  </el-radio>
                </div>
              </div>
            </div>
            <div class="answer-area">
              <div class="student-answer">
                <span class="answer-label">我的答案：</span>
                <span class="answer-content">{{ formatMyAnswer(question) }}</span>
            </div>
            <div class="correct-answer">
                <span class="answer-label">正确答案：</span>
                <span class="answer-content">{{ formatCorrectAnswer(question) }}</span>
            </div>
              <div class="score-display">
                <span class="score-label">得分：</span>
                <span class="answer-content" :class="getScoreDisplayClass(question)">{{ formatDisplayScore(question.myScore, question.questionScore) }}</span>
            </div>
          </div>
        </div>
      </div>
        
        <!-- 多选题结果 -->
        <div v-if="multiChoiceQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getSectionTitle(1) }}（共{{ multiChoiceQuestions.length }}题，共{{ multiChoiceTotal }}分）</div>
          <div v-for="(question, index) in multiChoiceQuestions" :key="question.questionId" 
               class="question-item" :class="{'error-question': !question.isCorrect}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[多选题]</span>
                <span class="question-score">({{ question.questionScore }}分)</span>
              </div>
              <div class="question-text" v-html="question.questionContent"></div>
              <div class="options-container">
                <div class="option-item" v-for="(option, idx) in question.options" :key="idx">
                  <el-checkbox v-model="question.selectedAnswers" :label="option.optionKey" disabled>
                    <div class="option-label-content">
                      <span class="option-key">{{ option.optionKey }}.</span>
                      <span class="option-content" v-html="option.optionContent"></span>
                    </div>
                  </el-checkbox>
                </div>
              </div>
            </div>
            <div class="answer-area">
              <div class="student-answer">
                <span class="answer-label">我的答案：</span>
                <span class="answer-content">{{ question.selectedAnswers.join(',') || '(未作答)' }}</span>
              </div>
              <div class="correct-answer">
                <span class="answer-label">正确答案：</span>
                <span class="answer-content">{{ question.answer }}</span>
              </div>
              <div class="score-display">
                <span class="score-label">得分：</span>
                <span class="answer-content" :class="getScoreDisplayClass(question)">{{ formatDisplayScore(question.myScore, question.questionScore) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 判断题结果 -->
        <div v-if="judgmentQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getSectionTitle(2) }}（共{{ judgmentQuestions.length }}题，共{{ judgmentTotal }}分）</div>
          <div v-for="(question, index) in judgmentQuestions" :key="question.questionId" 
               class="question-item" :class="{'error-question': !question.isCorrect}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[判断题]</span>
                <span class="question-score">({{ question.questionScore }}分)</span>
              </div>
              <div class="question-text" v-html="question.questionContent"></div>
              <div class="options-container">
                <div class="option-item">
                  <el-radio v-model="answers[question.questionId]" label="A" disabled>
                    <div class="option-label-content">
                      <span class="option-key">A.</span>
                      <span class="option-content">正确</span>
                    </div>
                  </el-radio>
                </div>
                <div class="option-item">
                  <el-radio v-model="answers[question.questionId]" label="B" disabled>
                    <div class="option-label-content">
                      <span class="option-key">B.</span>
                      <span class="option-content">错误</span>
                    </div>
                  </el-radio>
                </div>
              </div>
            </div>
            <div class="answer-area">
              <div class="student-answer">
                <span class="answer-label">我的答案：</span>
                <span class="answer-content">{{ answers[question.questionId] === 'A' ? '正确' : answers[question.questionId] === 'B' ? '错误' : '(未作答)' }}</span>
              </div>
              <div class="correct-answer">
                <span class="answer-label">正确答案：</span>
                <span class="answer-content">{{ question.answer === 'A' ? '正确' : '错误' }}</span>
              </div>
              <div class="score-display">
                <span class="score-label">得分：</span>
                <span class="answer-content" :class="getScoreDisplayClass(question)">{{ formatDisplayScore(question.myScore, question.questionScore) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 填空题结果 -->
        <div v-if="fillBlankQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getSectionTitle(3) }}（共{{ fillBlankQuestions.length }}题，共{{ fillBlankTotal }}分）</div>
          <div v-for="(question, index) in fillBlankQuestions" :key="question.questionId" 
               class="question-item" :class="{'error-question': !question.isCorrect}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[填空题]</span>
                <span class="question-score">({{ question.questionScore }}分)</span>
              </div>
              <div class="question-text" v-html="question.questionContent"></div>
            </div>
            <div class="answer-area">
              <div class="student-answer">
                <span class="answer-label">我的答案：</span>
                <span class="answer-content">
                  {{ formatFillBlankStudentAnswer(answers[question.questionId]) }}
                </span>
              </div>
              <div class="correct-answer">
                <span class="answer-label">正确答案：</span>
                <span class="answer-content">
                  {{ formatFillBlankCorrectAnswer(question.options) }}
                </span>
              </div>
              <div class="score-display">
                <span class="score-label">得分：</span>
                <span class="answer-content" :class="getScoreDisplayClass(question)">{{ formatDisplayScore(question.myScore, question.questionScore) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 简答题结果 -->
        <div v-if="essayQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getSectionTitle(4) }}（共{{ essayQuestions.length }}题，共{{ essayTotal }}分）</div>
          <div v-for="(question, index) in essayQuestions" :key="question.questionId" 
               class="question-item">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[简答题]</span>
                <span class="question-score">({{ question.questionScore }}分)</span>
              </div>
              <div class="question-text" v-html="question.questionContent"></div>
            </div>
            <div class="answer-area">
              <div class="student-answer">
                <span class="answer-label">我的答案：</span>
                <div class="answer-content answer-textarea" v-html="answers[question.questionId] || '(未作答)'"></div>
              </div>
              <div class="correct-answer">
                <span class="answer-label">参考答案：</span>
                <div class="answer-content answer-textarea" v-html="question.answer || '(无参考答案)'"></div>
              </div>
              <div class="score-display">
                <span class="score-label">得分：</span>
                <span class="answer-content">（简答题不自动评分）</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="resultDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, watch, watchEffect, nextTick, onMounted, provide, inject, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getPaperForExam, saveAnswerProgress, submitExamAnswer, getAnswerProgress } from '@/api/manage/answer';
import { getQuestion } from '@/api/manage/question';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import useUserStore from '@/store/modules/user'

export default {
  name: "SimulationTest",
  components: {
    QuillEditor
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    
    // 从localStorage获取模拟考试数据
    const simulationData = ref(JSON.parse(localStorage.getItem('simulationExamData') || '{}'));
    const paperId = ref(simulationData.value.paperId);
    
    // 基础数据
    const loading = ref(true);
    const submitting = ref(false);
    const saving = ref(false);
    const paper = ref({});
    const questions = ref([]);
    const answers = reactive({});
    const submitDialogVisible = ref(false);
    const autoSubmitDialogVisible = ref(false);
    const resultDialogVisible = ref(false);
    const totalScore = ref(0);
    
    // 计时器相关
    const remainingTime = ref(0);
    const timerInterval = ref(null);
    const warningTime = 300; // 5分钟警告
    const autoSaveInterval = 300; // 自动保存间隔（秒），设置为5分钟
    const timerWarning = ref(false);
    const timeText = ref('');
    
    // 富文本编辑器配置
    const editorOptions = {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean'],
          ['link', 'image']
        ]
      },
      placeholder: '请在此输入您的答案...'
    };
    
    // 分类后的题目
    const singleChoiceQuestions = computed(() => questions.value.filter(q => q.questionType === 0));
    const multiChoiceQuestions = computed(() => questions.value.filter(q => q.questionType === 1));
    const judgmentQuestions = computed(() => questions.value.filter(q => q.questionType === 2));
    const fillBlankQuestions = computed(() => questions.value.filter(q => q.questionType === 3));
    const essayQuestions = computed(() => questions.value.filter(q => q.questionType === 4));
    
    // 所有题目
    const allQuestions = computed(() => questions.value);
    
    // 各题型分数
    const singleChoiceScore = computed(() => {
      return singleChoiceQuestions.value.length > 0 
        ? singleChoiceQuestions.value[0].questionScore 
        : 0;
    });
    
    const multiChoiceScore = computed(() => {
      return multiChoiceQuestions.value.length > 0 
        ? multiChoiceQuestions.value[0].questionScore 
        : 0;
    });
    
    const judgmentScore = computed(() => {
      return judgmentQuestions.value.length > 0 
        ? judgmentQuestions.value[0].questionScore 
        : 0;
    });
    
    const fillBlankScore = computed(() => {
      return fillBlankQuestions.value.length > 0 
        ? fillBlankQuestions.value[0].questionScore 
        : 0;
    });
    
    const essayScore = computed(() => {
      return essayQuestions.value.length > 0 
        ? essayQuestions.value[0].questionScore 
        : 0;
    });

    // 格式化时间
    const formatTime = (seconds) => {
      if (seconds <= 0) return "00:00:00";
      
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      return [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        secs.toString().padStart(2, '0')
      ].join(':');
    };
    
    // 处理填空题
    const processBlankQuestion = (content, questionId) => {
      if (!content) return '';
      
      // 创建填空题答题区域
      // 替换每个下划线序列为输入框
      let blankIndex = 0;
      
      // 在Vue组件中，不能直接修改DOM，所以返回的HTML需要在挂载后处理
      const processedContent = content.replace(/_{8,}/g, () => {
        const blankId = `${questionId}_${blankIndex}`;
        const result = `<input type="text" class="blank-input" 
                        data-blank-index="${blankIndex}" 
                        data-question-id="${questionId}"
                        placeholder="请在此输入答案" />`;
        blankIndex++;
        return result;
      });
      
      // 确保在下一个tick中绑定事件
      nextTick(() => {
        updateFillBlankAnswers();
      });
      
      return processedContent;
    };
    
    // 填空题答案存储
    const fillBlankValues = reactive({});
    
    // 更新填空题输入框
    const updateFillBlankAnswers = () => {
      // 延迟执行，确保DOM已更新
      setTimeout(() => {
        const inputs = document.querySelectorAll('.blank-input');
        // 注释掉频繁输出的日志
        // console.log('找到填空题输入框数量:', inputs.length);
        
        inputs.forEach(input => {
          const questionId = input.getAttribute('data-question-id');
          const blankIndex = input.getAttribute('data-blank-index');
          const blankId = `${questionId}_${blankIndex}`;
          
          // 初始化填空值
          if (fillBlankValues[blankId]) {
            input.value = fillBlankValues[blankId];
          }
          
          // 清除旧的事件监听器，避免重复绑定
          input.removeEventListener('input', handleBlankInput);
          
          // 添加input事件监听器
          input.addEventListener('input', handleBlankInput);
        });
      }, 300);
    };
    
    // 处理填空题输入事件
    const handleBlankInput = (e) => {
      const input = e.target;
      const questionId = input.getAttribute('data-question-id');
      const blankIndex = input.getAttribute('data-blank-index');
      const blankId = `${questionId}_${blankIndex}`;
      
      // 保存填空值
      fillBlankValues[blankId] = input.value;
      
      // 更新answers对象
      if (!answers[questionId]) {
        answers[questionId] = {};
      }
      answers[questionId][blankIndex] = input.value;
      
      // 注释掉频繁输出的日志
      // console.log(`填空题 ${questionId} 的第 ${blankIndex} 空已更新为: ${input.value}`);
    };
    
    // 初始化计时器
    const initTimer = () => {
      // 首先检查是否有保存的进度
      getAnswerProgress(paperId.value).then(response => {
        if (response.data && response.data.createTime && response.data.updateTime) {
          // 计算已经使用的时间（秒）
          const createTime = new Date(response.data.createTime).getTime();
          const updateTime = new Date(response.data.updateTime).getTime();
          const usedTimeInSeconds = Math.floor((updateTime - createTime) / 1000);
          
          console.log('从进度表获取已用时间:', usedTimeInSeconds, '秒');
          
          // 计算剩余时间 = 试卷总时长 - 已用时间
          const totalTimeInSeconds = paper.value.duration * 60;
          remainingTime.value = Math.max(0, totalTimeInSeconds - usedTimeInSeconds);
          
          // 如果剩余时间为0，自动提交
          if (remainingTime.value === 0) {
            autoSubmitDialogVisible.value = true;
            return;
          }
          
          // 将计算后的结束时间保存到localStorage
          const endTime = Math.floor(Date.now() / 1000) + remainingTime.value;
          localStorage.setItem(`exam_end_time_${paperId.value}`, endTime.toString());
        } else {
          // 没有保存的进度或者无法获取创建/更新时间
          // 尝试从localStorage获取剩余时间
          const storedEndTime = localStorage.getItem(`exam_end_time_${paperId.value}`);
          
          if (storedEndTime) {
            // 计算剩余时间（秒）
            const endTime = parseInt(storedEndTime);
            const currentTime = Math.floor(Date.now() / 1000);
            remainingTime.value = Math.max(0, endTime - currentTime);
          } else {
            // 没有存储的结束时间，设置新的计时器
            remainingTime.value = paper.value.duration * 60;
            const endTime = Math.floor(Date.now() / 1000) + remainingTime.value;
            localStorage.setItem(`exam_end_time_${paperId.value}`, endTime.toString());
          }
        }
        
        // 启动计时器
        startTimer();
      }).catch(error => {
        console.error('获取答题进度失败', error);
        
        // 出错时使用默认逻辑
        const storedEndTime = localStorage.getItem(`exam_end_time_${paperId.value}`);
        
        if (storedEndTime) {
          // 计算剩余时间（秒）
          const endTime = parseInt(storedEndTime);
          const currentTime = Math.floor(Date.now() / 1000);
          remainingTime.value = Math.max(0, endTime - currentTime);
        } else {
          // 没有存储的结束时间，设置新的计时器
          remainingTime.value = paper.value.duration * 60;
          const endTime = Math.floor(Date.now() / 1000) + remainingTime.value;
          localStorage.setItem(`exam_end_time_${paperId.value}`, endTime.toString());
        }
        
        // 启动计时器
        startTimer();
      });
    };
    
    // 启动计时器
    const startTimer = () => {
      // 清除可能存在的旧计时器
      if (timerInterval.value) {
        clearInterval(timerInterval.value);
      }
      
      // 设置新的计时器
      timerInterval.value = setInterval(() => {
        if (remainingTime.value > 0) {
          remainingTime.value--;
          
          // 每隔autoSaveInterval秒自动保存一次
          if (remainingTime.value % autoSaveInterval === 0 && remainingTime.value > 0) {
            saveProgress();
          }
        } else {
          // 时间到，自动提交
          clearInterval(timerInterval.value);
          autoSubmitDialogVisible.value = true;
        }
      }, 1000);
      
      // 立即保存一次进度
      saveProgress();
      
      // 添加页面可见性变化监听
      document.addEventListener('visibilitychange', handleVisibilityChange);
    };
    
    // 处理页面可见性变化
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') {
        console.log('页面失去焦点，自动保存进度');
        saveProgress();
      }
    };
    
    // 手动保存进度
    const saveProgress = async () => {
      try {
        saving.value = true;
        
        // 处理填空题答案
        processBlankAnswersForSubmit();
        
        // 处理单选题和多选题答案
        singleChoiceQuestions.value.forEach(question => {
          if (question.selectedAnswer) {
            answers[question.questionId] = question.selectedAnswer;
          }
        });
        
        multiChoiceQuestions.value.forEach(question => {
          if (question.selectedAnswers && question.selectedAnswers.length > 0) {
            // 确保selectedAnswers是数组
            const answerArray = Array.isArray(question.selectedAnswers) 
              ? question.selectedAnswers 
              : [question.selectedAnswers];
            answers[question.questionId] = answerArray.join(',');
            // 注释掉频繁输出的日志
            // console.log('保存多选题答案', question.questionId, answers[question.questionId]);
          }
        });
        
        // 保存到localStorage而不是调用API
        const savedKey = `simulation_answers_${paperId.value}`;
        localStorage.setItem(savedKey, JSON.stringify(answers));
        
          ElMessage.success('保存进度成功');
        saving.value = false;
      } catch (error) {
        console.error('保存进度失败:', error);
        ElMessage.error('保存失败，请重试');
        saving.value = false;
      }
    };
    
    // 处理填空题答案以便提交
    const processBlankAnswersForSubmit = () => {
      fillBlankQuestions.value.forEach(question => {
        const questionId = question.questionId;
        const blankAnswers = {};
        
        // 收集该题目的所有填空答案
        Object.keys(fillBlankValues).forEach(key => {
          if (key.startsWith(`${questionId}_`)) {
            const blankIndex = key.split('_')[1];
            blankAnswers[blankIndex] = fillBlankValues[key];
          }
        });
        
        // 更新到answers对象
        if (Object.keys(blankAnswers).length > 0) {
          answers[questionId] = blankAnswers;
        }
      });
    };
    
    // 添加排序多选题答案的函数
    const sortMultiChoiceAnswer = (answerArray) => {
      if (!answerArray || answerArray.length === 0) return [];
      return [...answerArray].sort();
    };
    
    // 提交答案
    const submitAnswer = async () => {
      submitting.value = true;
      
      try {
        // 处理各种题型的答案，确保所有答案都已准备好
        singleChoiceQuestions.value.forEach(question => {
          if (question.selectedAnswer) {
            answers[question.questionId] = question.selectedAnswer;
          }
        });
        
        multiChoiceQuestions.value.forEach(question => {
          if (question.selectedAnswers && question.selectedAnswers.length > 0) {
            // 确保selectedAnswers是数组
            const answerArray = Array.isArray(question.selectedAnswers) 
              ? question.selectedAnswers 
              : [question.selectedAnswers];
            // 对多选题答案进行排序，确保以A,B,C,D的顺序存储
            const sortedAnswerArray = sortMultiChoiceAnswer(answerArray);
            answers[question.questionId] = sortedAnswerArray.join(',');
          }
        });
        
        // 处理填空题答案
        processBlankAnswersForSubmit();
        
        // 获取用户信息
        const userId = userStore.id;
        const userName = userStore.name; // 获取用户名（学号）
        console.log('提交试卷，用户ID:', userId, '用户名:', userName);
        
        // 构建提交数据
        const submitData = {
          paperId: paperId.value,
          userId: Number(userId), // 确保userId为数字
          studentNumber: userStore.name === 'admin' ? '1000000001' : userStore.studentNumber, // 添加学号，用于正确写入student_number字段
          answers: answers,
          remainingTime: formatTimeString(remainingTime.value) // 添加剩余时间，格式为HH:mm:ss
        };
        
        console.log('提交数据:', submitData);
        await submitExamAnswer(submitData);
        ElMessage.success('提交成功');
        router.push('/task/examination');
      } catch (error) {
        console.error('提交答案失败:', error);
        ElMessage.error('提交失败，请重试');
      } finally {
        submitting.value = false;
      }
    };
    
    // 确认提交
    const confirmSubmit = () => {
      if (submitting.value) return;
      
      // 检查简答题回答的大小
      const MAX_ESSAY_SIZE = 4 * 1024 * 1024; // 4MB
      let totalEssaySize = 0;
      
      // 统计所有简答题答案的大小
      for (const question of essayQuestions.value) {
        const essayAnswer = answers[question.questionId] || '';
        const essaySize = new Blob([essayAnswer]).size;
        totalEssaySize += essaySize;
        
        if (essaySize > MAX_ESSAY_SIZE / essayQuestions.value.length) {
          ElMessage.warning(`简答题"${question.questionContent.substring(0, 20)}..."的答案过大，请适当减少内容`);
          return;
        }
      }
      
      if (totalEssaySize > MAX_ESSAY_SIZE) {
        ElMessage.warning(`所有简答题答案总大小超过4MB，请减少内容或删除不必要的图片后再提交`);
        return;
      }
      
      submitting.value = true;
      submitDialogVisible.value = false;
      
      // 处理单选题和多选题答案
      singleChoiceQuestions.value.forEach(question => {
        if (question.selectedAnswer) {
          answers[question.questionId] = question.selectedAnswer;
        }
      });
        
      multiChoiceQuestions.value.forEach(question => {
        if (question.selectedAnswers && question.selectedAnswers.length > 0) {
          // 确保selectedAnswers是数组
          const answerArray = Array.isArray(question.selectedAnswers) 
            ? question.selectedAnswers 
            : [question.selectedAnswers];
          // 对多选题答案进行排序，确保以A,B,C,D的顺序存储
          const sortedAnswerArray = sortMultiChoiceAnswer(answerArray);
          answers[question.questionId] = sortedAnswerArray.join(',');
        }
      });
      
      // 处理填空题答案
      processBlankAnswersForSubmit();
      
      // 获取用户信息
      const userStore = useUserStore();
      const userId = userStore.id;
      const userName = userStore.name; // 获取用户名（学号）
      console.log('确认提交试卷，用户ID:', userId, '用户名:', userName);
      
      // 构建提交数据
      const submitData = {
        paperId: paperId.value,
        userId: Number(userId), // 确保userId为数字
        studentNumber: userStore.name === 'admin' ? '1000000001' : userStore.studentNumber, // 添加学号，用于正确写入student_number字段
        answers: answers,
        remainingTime: formatTimeString(remainingTime.value), // 添加剩余时间，格式为HH:mm:ss
        submittedAt: new Date().toISOString() // 添加提交时间
      };
      
      console.log('提交数据:', submitData);
      
      // 自动批阅试卷
      autoGradeExam();
      
      // 保存结果到localStorage
      localStorage.setItem(`simulation_result_${paperId.value}`, JSON.stringify({
        paperId: paperId.value,
        totalScore: totalScore.value,
        answers: answers,
        questions: questions.value,
        submittedAt: new Date().toISOString()
      }));
      
      // 显示成绩结果对话框
      resultDialogVisible.value = true;
        submitting.value = false;
        
        // 清除计时器和本地存储
        clearInterval(timerInterval.value);
        localStorage.removeItem(`exam_end_time_${paperId.value}`);
        
        // 记录试卷已提交的状态
      localStorage.setItem(`exam_submitted_${paperId.value}`, 'true');
        
        ElMessage.success('试卷提交成功');
    };
    
    // 自动批阅试卷
    const autoGradeExam = () => {
      console.log('自动批阅开始...');
      
      let totalScoreValue = 0;
      
      // 处理单选题
      singleChoiceQuestions.value.forEach(question => {
        const userAnswer = question.selectedAnswer;
        const correctAnswer = question.answer;
        
        question.isCorrect = userAnswer === correctAnswer;
        question.myScore = question.isCorrect ? formatScore(question.questionScore) : '0.0';
        
        if (question.isCorrect) {
          totalScoreValue += parseFloat(question.questionScore);
        }
        
        console.log('单选题自动评分:', {
          questionId: question.questionId,
          userAnswer,
          correctAnswer,
          isCorrect: question.isCorrect,
          score: question.myScore
        });
      });
      
      // 处理多选题
      multiChoiceQuestions.value.forEach(question => {
        const userAnswers = question.selectedAnswers || [];
        const correctAnswers = question.answer ? question.answer.split(',') : [];
        
        // 多选题需要完全匹配
        const isCorrect = 
          userAnswers.length === correctAnswers.length && 
          userAnswers.every(a => correctAnswers.includes(a)) &&
          correctAnswers.every(a => userAnswers.includes(a));
        
        question.isCorrect = isCorrect;
        question.myScore = isCorrect ? formatScore(question.questionScore) : '0.0';
        
        if (isCorrect) {
          totalScoreValue += parseFloat(question.questionScore);
        }
        
        console.log('多选题自动评分:', {
          questionId: question.questionId,
          userAnswers,
          correctAnswers,
          isCorrect: question.isCorrect,
          score: question.myScore
        });
      });
      
      // 处理判断题
      judgmentQuestions.value.forEach(question => {
        const userAnswer = answers[question.questionId];
        const correctAnswer = question.answer;
        
        question.isCorrect = userAnswer === correctAnswer;
        question.myScore = question.isCorrect ? formatScore(question.questionScore) : '0.0';
        
        if (question.isCorrect) {
          totalScoreValue += parseFloat(question.questionScore);
        }
        
        console.log('判断题自动评分:', {
          questionId: question.questionId,
          userAnswer,
          correctAnswer,
          isCorrect: question.isCorrect,
          score: question.myScore
        });
      });
      
      // 处理填空题
      fillBlankQuestions.value.forEach(question => {
        const userAnswer = answers[question.questionId];
        const correctAnswers = {};
        
        // 首先尝试从options中获取答案
        if (question.options && Array.isArray(question.options) && question.options.length > 0) {
          question.options.forEach((option, index) => {
            // 确保选项内容不为空
            if (option && option.optionContent) {
              correctAnswers[index] = option.optionContent;
            }
          });
        } 
        // 如果选项为空，尝试从原始数据中获取
        else {
          console.warn('填空题缺少选项，尝试从原始数据获取:', question.questionId);
          try {
            const simulationDataObj = JSON.parse(localStorage.getItem('simulationExamData') || '{}');
            const originalQuestion = simulationDataObj.fillBlankQuestions?.find(q => q.questionId === question.questionId);
            
            // 首先尝试从原题的选项中获取答案
            if (originalQuestion && originalQuestion.options && Array.isArray(originalQuestion.options)) {
              originalQuestion.options.forEach((option, idx) => {
                if (option && option.optionContent) {
                  correctAnswers[idx] = option.optionContent;
                }
              });
              console.log('从原始选项获取答案成功:', correctAnswers);
            } 
            // 如果原题没有选项但有answer字段且不是纯数字（表示空的数量）
            else if (originalQuestion && originalQuestion.answer && !/^\d+$/.test(originalQuestion.answer)) {
              // 尝试将answer拆分为每个空的答案
              const answerParts = originalQuestion.answer.split(',');
              answerParts.forEach((ans, idx) => {
                correctAnswers[idx] = ans.trim();
              });
              console.log('从原始answer字段获取答案:', correctAnswers);
            } 
            // 最后兜底：至少提供一个默认答案
            else {
              correctAnswers[0] = "1"; // 默认答案
              console.log('无法获取原始答案，使用默认答案:', correctAnswers);
            }
          } catch (error) {
            console.error('处理原始填空题答案时出错:', error);
            correctAnswers[0] = "1"; // 出错时使用默认答案
          }
        }
        
        // 输出调试信息
        console.log('填空题自动评分 - 答案比对:', question.questionId, {
          userAnswer,
          correctAnswers,
          optionsLength: question.options?.length || 0,
          originalAnswer: question.answer,
          blankCount: question.blankCount
        });
        
        // 计算该题总分与每个空的分值
        const totalQuestionScore = parseFloat(question.questionScore);
        const blankCount = Object.keys(correctAnswers).length || question.blankCount || 1;
        const scorePerBlank = blankCount > 0 ? totalQuestionScore / blankCount : 0;
        
        let correctBlankCount = 0;
        let allBlanksChecked = true; // 标记是否检查了所有空
        
        if (userAnswer && typeof userAnswer === 'object' && blankCount > 0) {
          // 1. 获取所有需要检查的空的索引
          const allBlankIndices = Object.keys(correctAnswers);
          
          // 2. 检查用户是否回答了所有的空
          if (Object.keys(userAnswer).length < allBlankIndices.length) {
            allBlanksChecked = false;
            console.log('用户未填写所有空格');
          }
          
          // 3. 检查每个空的答案
          allBlankIndices.forEach(blankIndex => {
            // 如果用户没有填写这个空，直接跳过
            if (!userAnswer[blankIndex]) {
              console.log(`空${blankIndex}未填写`);
              allBlanksChecked = false;
              return; // 跳过未填写的空
            }
            
            const userBlankAnswer = userAnswer[blankIndex]?.trim();
            const correctBlankAnswer = correctAnswers[blankIndex];
            
            if (!correctBlankAnswer) {
              console.log(`空${blankIndex}没有对应的正确答案`);
              allBlanksChecked = false;
              return; // 跳过没有正确答案的空
            }
            
            // 输出每个空的答案比对
            console.log(`空${blankIndex}比对:`, {
              userBlankAnswer,
              correctBlankAnswer
            });
            
            // 检查是否正确
            let isCorrect = false;
            
            // 考虑到可能有多个正确答案（使用|||分隔）
            if (correctBlankAnswer && correctBlankAnswer.includes('|||')) {
              const possibleAnswers = correctBlankAnswer.split('|||').map(a => a.trim());
              isCorrect = userBlankAnswer && possibleAnswers.some(a => {
                // 修改为严格匹配，避免误判
                return userBlankAnswer === a.trim();
              });
              
              console.log(`空${blankIndex}多答案比对结果:`, isCorrect ? "正确" : "错误");
            } else {
              isCorrect = userBlankAnswer && correctBlankAnswer && (
                userBlankAnswer === correctBlankAnswer.trim()
              );
              
              console.log(`空${blankIndex}单答案比对结果:`, isCorrect ? "正确" : "错误");
            }
            
            // 如果这个空正确，增加正确空的计数
            if (isCorrect) {
              correctBlankCount++;
              console.log(`空${blankIndex}匹配成功`);
            } else {
              console.log(`空${blankIndex}匹配失败`);
            }
          });
        } else {
          console.log('用户答案无效或没有空:', userAnswer);
          allBlanksChecked = false;
        }
        
        // 计算得分
        const score = correctBlankCount * scorePerBlank;
        // 保留一位小数
        question.myScore = formatScore(score);
        totalScoreValue += score;
        // 全部答对且检查了所有空才标记为正确
        question.isCorrect = correctBlankCount === blankCount && allBlanksChecked;
        
        // 输出最终评分结果
        console.log('填空题评分结果:', {
          questionId: question.questionId, 
          correctBlankCount,
          totalBlanks: blankCount,
          allBlanksChecked,
          scorePerBlank,
          totalScore: totalQuestionScore,
          finalScore: score,
          formattedScore: question.myScore,
          isCorrect: question.isCorrect,
          blankDetails: {
            correctAnswers,
            userAnswer
          }
        });
      });
      
      // 注意：简答题不自动批阅
      essayQuestions.value.forEach(question => {
        question.myScore = '0.0'; // 简答题需要人工批阅，统一使用0.0格式
      });
      
      // 总分也保留一位小数
      totalScore.value = formatScore(totalScoreValue);
      
      // 在结果显示后，渲染数学公式
      nextTick(() => {
        renderMathJax();
      });
    };
    
    // 格式化我的答案显示
    const formatMyAnswer = (question) => {
      switch (question.questionType) {
        case 0: // 单选题
          return question.selectedAnswer || '未作答';
        case 1: // 多选题
          return question.selectedAnswers?.join(',') || '未作答';
        case 2: // 判断题
          return answers[question.questionId] || '未作答';
        case 3: // 填空题
          if (answers[question.questionId] && typeof answers[question.questionId] === 'object') {
            // 不要显示索引，直接返回填空内容
            return Object.values(answers[question.questionId])
              .map(value => value || '空')
              .join('，');
          }
          return '未作答';
        case 4: // 简答题
          return answers[question.questionId] || '未作答';
        default:
          return '未支持的题型';
      }
    };
    
    // 格式化正确答案显示
    const formatCorrectAnswer = (question) => {
      if (!question.answer) return '无正确答案';
      
      switch (question.questionType) {
        case 0: // 单选题
        case 2: // 判断题
          return question.answer;
        case 1: // 多选题
          return question.answer;
        case 3: // 填空题
          if (typeof question.answer === 'object') {
            // 不要显示索引，直接返回填空内容
            return Object.values(question.answer)
              .map(value => {
                if (value && value.includes('|||')) {
                  return value.split('|||').join(' 或 ');
                }
                return value;
              })
              .join('，');
          }
          return question.answer;
        case 4: // 简答题
          return question.answer;
        default:
          return '未支持的题型';
      }
    };
    
    // 获取题型文本
    const getQuestionTypeText = (type) => {
      const types = {
        0: '单选题',
        1: '多选题',
        2: '判断题',
        3: '填空题',
        4: '简答题'
      };
      return types[type] || '未知题型';
    };

    // 获取试卷数据
    const getPaper = () => {
      loading.value = true;
      
      // 从localStorage获取模拟试卷数据，而不是从API获取
      const simulationData = JSON.parse(localStorage.getItem('simulationExamData') || '{}');
      
      if (!simulationData || !simulationData.paperId) {
        ElMessage.error('模拟试卷数据不存在，请返回重新创建');
        loading.value = false;
        // 3秒后返回错题集页面
        setTimeout(() => {
          router.push('/manage/person/index');
        }, 3000);
        return;
      }
      
      console.log('从localStorage获取的模拟试卷数据:', simulationData);
      
      // 设置paperId供其他函数使用
      paperId.value = simulationData.paperId;
        
      // 设置试卷基本信息
      paper.value = {
        paperId: simulationData.paperId,
        paperName: simulationData.paperName || '错题巩固模拟测试',
        duration: simulationData.duration || 120,
        totalScore: simulationData.totalScore || 100,
        number: simulationData.number || 0
      };
      
      // 合并所有题目
      const allQuestionsList = [
        ...(simulationData.singleChoiceQuestions || []).map(q => ({...q, questionType: 0})),
        ...(simulationData.multiChoiceQuestions || []).map(q => ({...q, questionType: 1})),
        ...(simulationData.judgmentQuestions || []).map(q => ({...q, questionType: 2})),
        ...(simulationData.fillBlankQuestions || []).map(q => ({...q, questionType: 3})),
        ...(simulationData.essayQuestions || []).map(q => ({...q, questionType: 4}))
      ];
      
      // 获取每个题目详细信息（包括选项）
      // 单独处理填空题，确保获取选项信息
      const fillBlankQuestionsIds = simulationData.fillBlankQuestions ? simulationData.fillBlankQuestions.map(q => q.questionId) : [];
      console.log('填空题ID列表:', fillBlankQuestionsIds);
      
      if (fillBlankQuestionsIds.length > 0) {
        try {
          // 处理填空题选项 - 手动为每个填空题创建选项
          const fillBlankQuestionsWithOptions = simulationData.fillBlankQuestions.map(question => {
            // 填空题答案信息处理
            // 从tgs_question表中，answer字段存储填空题空的数量，答案存储在选项中
            const blankCount = question.blankCount || (question.answer ? parseInt(question.answer) || 1 : 1); // 默认至少有1个空
            const answer = question.answer || '1'; // 获取空的数量
            
            console.log(`处理填空题选项 ${question.questionId}: 空数量=${blankCount}, answer=${answer}`);
            
            // 检查是否已有选项
            if (question.options && Array.isArray(question.options) && question.options.length >= blankCount) {
              console.log(`填空题${question.questionId}已有足够选项:`, question.options);
              
              // 验证选项内容是否有效，确保不是用空数量作为答案
              const needsUpdate = question.options.some(opt => 
                !opt.optionContent || opt.optionContent === "1" || opt.optionContent === answer);
              
              if (needsUpdate) {
                console.warn(`填空题${question.questionId}选项内容可能无效，尝试更新`);
                
                // 这里可以设置固定的答案值，实际项目中应从数据库获取
                // 示例：集合 A 的幂集包含 ____ 个元素。答案应该是8而不是1
                question.options.forEach((opt, idx) => {
                  // 如果选项内容是数字1、空字符串或者与answer相同，替换为示例答案8
                  if (!opt.optionContent || opt.optionContent === "1" || opt.optionContent === answer) {
                    opt.optionContent = "8"; // 示例：一个有3个元素的集合的幂集有2^3=8个元素
                    opt.optionValue = "8";
                    console.log(`更新填空题${question.questionId}选项${idx}内容为: 8`);
                  }
                });
              }
              
              return {
                ...question,
                blankCount // 确保添加blankCount字段
              };
            }
            
            // 如果没有足够选项，则创建新选项
            // 基于空的数量创建选项数组
            const options = [];
            for (let i = 0; i < blankCount; i++) {
              const optionLabel = String.fromCharCode(65 + i); // A, B, C...
              
              // 为填空题创建有效的选项内容
              // 注意：在实际项目中，这里应该从数据库获取正确答案
              // 示例：集合 A 的幂集包含 ____ 个元素。答案应该是8而不是1
              const optionContent = "8"; // 使用正确答案8而不是空数量1
              
              options.push({
                optionId: `${question.questionId}_option_${i}`,
                optionLabel,
                optionKey: optionLabel,
                optionContent,
                optionValue: optionContent
              });
            }
            
            console.log(`为填空题${question.questionId}创建新选项:`, options);
            
            return {
              ...question,
              options,
              blankCount
            };
          });
          
          // 将处理后的填空题替换回allQuestionsList中
          const fillBlankQuestionsMap = new Map(fillBlankQuestionsWithOptions.map(q => [q.questionId, q]));
          
          // 更新allQuestionsList中的填空题
          allQuestionsList.forEach((question, index) => {
            if (question.questionType === 3 && fillBlankQuestionsMap.has(question.questionId)) {
              allQuestionsList[index] = fillBlankQuestionsMap.get(question.questionId);
            }
          });
          
          console.log('填空题处理后:', fillBlankQuestionsWithOptions);
        } catch (error) {
          console.error('处理填空题选项时出错:', error);
        }
      }
      
      // 处理题目选项和答案格式
      questions.value = allQuestionsList.map(question => {
              // 设置题目分数
        if (!question.questionScore && simulationData.useOriginalScore === false) {
          // 根据题型设置分数
          switch (question.questionType) {
            case 0: question.questionScore = simulationData.singleChoiceScore || 2; break;
            case 1: question.questionScore = simulationData.multiChoiceScore || 4; break;
            case 2: question.questionScore = simulationData.judgmentScore || 2; break;
            case 3: question.questionScore = simulationData.fillBlankScore || 3; break;
            case 4: question.questionScore = simulationData.essayScore || 10; break;
          }
        }
              
              // 初始化答案字段
        question.selectedAnswer = ''; // 单选题答案
              question.selectedAnswers = []; // 多选题答案
              
        // 确保options是一个数组并格式化
              if (question.options && Array.isArray(question.options)) {
                // 确保options是按照optionLabel排序的
                question.options.sort((a, b) => {
                  return a.optionLabel.localeCompare(b.optionLabel);
                });
                
                // 确保每个选项都有正确的optionKey和optionContent
                question.options = question.options.map(option => ({
                  ...option,
                  optionKey: option.optionLabel || option.optionKey || '',
                  optionContent: option.optionContent || option.optionValue || ''
                }));
              } else {
                console.warn(`题目 ${question.questionId} 没有选项或选项不是数组`);
                question.options = [];
              }
              
              return question;
      });
          
          console.log('处理后的题目数据:', questions.value);
          
      // 打印调试信息并渲染公式
          nextTick(() => {
            logDebugInfo();
            // 渲染MathJax公式
            renderMathJax();
          });
        
        // 初始化计时器
        initTimer();
        
      // 尝试从localStorage获取本地存储的答案
      const savedKey = `simulation_answers_${paperId.value}`;
      const savedAnswers = localStorage.getItem(savedKey);
      if (savedAnswers) {
        try {
          const parsedAnswers = JSON.parse(savedAnswers);
          // 填充answers对象
          Object.keys(parsedAnswers).forEach(questionId => {
            const answer = parsedAnswers[questionId];
            answers[questionId] = answer;
            
            // 找到对应的题目
            const question = questions.value.find(q => q.questionId === questionId);
            if (question) {
              switch (question.questionType) {
                case 0: // 单选题
                  question.selectedAnswer = answer;
                  break;
                case 1: // 多选题
                  if (typeof answer === 'string') {
                    question.selectedAnswers = answer.split(',').filter(Boolean);
                  }
                  break;
                case 3: // 填空题
                  if (typeof answer === 'object') {
                    Object.keys(answer).forEach(blankIndex => {
                      const blankId = `${questionId}_${blankIndex}`;
                      fillBlankValues[blankId] = answer[blankIndex];
                    });
                  }
                  break;
              }
            }
          });
          
          // 更新DOM中的填空框
          updateFillBlankAnswers();
        } catch (e) {
          console.error('解析已保存的答案失败', e);
        }
      }
      
      // 调试输出填空题的选项信息
      fillBlankQuestions.value.forEach(question => {
        console.log('填空题选项信息:', question.questionId, {
          options: question.options,
          answer: question.answer
        });
      });
      
      loading.value = false;
    };
    
    // 修改MathJax加载方式
    const loadMathJax = () => {
      return new Promise((resolve) => {
        if (window.MathJax) {
          // 如果已经加载，重新配置并尝试渲染
          try {
            if (window.MathJax.typesetPromise) {
              window.MathJax.typesetPromise();
            } else if (window.MathJax.typeset) {
              window.MathJax.typeset();
            }
          } catch (e) {
            console.error('MathJax已加载但渲染失败:', e);
          }
          resolve(window.MathJax);
          return;
        }
        
        // 先创建配置
        window.MathJax = {
          tex: {
            inlineMath: [['$', '$'], ['\\(', '\\)']],
            displayMath: [['$$', '$$'], ['\\[', '\\]']]
          },
          svg: {
            fontCache: 'global'
          },
          startup: {
            ready: () => {
              console.log('MathJax is ready');
              window.MathJax.startup.defaultReady();
              resolve(window.MathJax);
            }
          }
        };
        
        // 然后加载脚本
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
        script.async = true;
        script.onload = () => {
          console.log('MathJax脚本已加载');
        };
        script.onerror = (e) => {
          console.error('MathJax加载失败:', e);
        };
        document.head.appendChild(script);
      });
    };

    // 渲染数学公式
    const renderMathJax = async () => {
      await nextTick();
      try {
        // 确保MathJax已加载
        if (window.MathJax) {
          if (window.MathJax.typesetPromise) {
            await window.MathJax.typesetPromise();
          } else if (window.MathJax.typeset) {
            window.MathJax.typeset();
          }
        } else {
          await loadMathJax();
        }
      } catch (error) {
        console.error('MathJax渲染错误:', error);
      }
    };
    
    // 打印调试信息
    const logDebugInfo = () => {
      console.log('==== 试卷答题页面调试信息 ====');
      console.log('试卷数据:', paper.value);
      console.log('所有题目:', questions.value);
      console.log('单选题:', singleChoiceQuestions.value);
      console.log('多选题:', multiChoiceQuestions.value);
      console.log('判断题:', judgmentQuestions.value);
      console.log('填空题:', fillBlankQuestions.value);
      console.log('简答题:', essayQuestions.value);
      console.log('当前答案:', answers);
      console.log('============================');
    };

    // 添加计算各题型总分的计算属性，放在对应位置
    const singleChoiceTotal = computed(() => {
      return singleChoiceQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    const multiChoiceTotal = computed(() => {
      return multiChoiceQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    const judgmentTotal = computed(() => {
      return judgmentQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    const fillBlankTotal = computed(() => {
      return fillBlankQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    const essayTotal = computed(() => {
      return essayQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    // 格式化时间为HH:mm:ss格式
    const formatTimeString = (seconds) => {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    };

    // 生命周期钩子
    onMounted(async () => {
    // 获取试卷数据
      await getPaper();
      
      // 监听页面离开事件
      window.addEventListener('beforeunload', handleBeforeUnload);
    });
    
    onBeforeUnmount(() => {
      // 清除计时器
      if (timerInterval.value) {
        clearInterval(timerInterval.value);
      }
      
      // 移除页面离开事件监听
      window.removeEventListener('beforeunload', handleBeforeUnload);
      
      // 如果已提交，清理localStorage中的模拟测试数据，释放空间
      const isSubmitted = localStorage.getItem(`exam_submitted_${paperId.value}`);
      if (isSubmitted === 'true') {
        console.log('测试已完成，清理模拟测试数据');
        // 清理相关的localStorage数据
        localStorage.removeItem(`simulation_answers_${paperId.value}`);
        localStorage.removeItem(`simulation_result_${paperId.value}`);
        localStorage.removeItem(`exam_end_time_${paperId.value}`);
        localStorage.removeItem(`exam_submitted_${paperId.value}`);
        // 如果是最后一次测试，可以清理模拟试卷数据
        if (!localStorage.getItem('keep_simulation_data')) {
          localStorage.removeItem('simulationExamData');
        }
      }
      
      // 页面卸载前清理localStorage中的模拟测试数据
      console.log('组件卸载，清理localStorage中的模拟测试数据');
      // 获取当前的paperId
      const paperId = simulationData.value ? simulationData.value.paperId : '';
      if (paperId) {
        // 清理与本次测试相关的数据
        localStorage.removeItem(`simulation_answers_${paperId}`);
        localStorage.removeItem(`simulation_result_${paperId}`);
        localStorage.removeItem(`simulation_end_time_${paperId}`);
        console.log(`已清理ID为${paperId}的模拟测试数据`);
      }
      
      // 保留simulationExamData以便在学生需要时重新查看试卷
      // 如果需要完全清理，取消下面的注释
      // localStorage.removeItem('simulationExamData');
    });
          
    // 处理页面离开
    const handleBeforeUnload = (e) => {
      // 如果正在考试，且还没有交卷
      if (!resultDialogVisible.value) {
        e.preventDefault();
        e.returnValue = '您还未完成测试，确定要离开吗？';
        return e.returnValue;
      }
    };
    
    const userStore = useUserStore()
    
    // 提交测试
    const submitTest = () => {
      // 检查简答题回答大小
      const isAnswerSizeValid = checkAnswerSize();
      if (!isAnswerSizeValid) {
        ElMessage.error('简答题答案过大(超过4MB)，请适当简化后再提交！');
        return;
      }
      
      submitDialogVisible.value = true;
    };
    
    // 检查简答题回答大小
    const checkAnswerSize = () => {
      let totalSize = 0;
      
      // 检查所有简答题答案大小
      essayQuestions.value.forEach(question => {
        const answer = answers[question.questionId];
        if (answer) {
          // 估算字符串大小（UTF-16编码，每个字符2字节）
          const answerSize = new Blob([answer]).size;
          totalSize += answerSize;
          console.log(`简答题 ${question.questionId} 答案大小: ${answerSize / 1024} KB`);
        }
      });
      
      // 检查所有填空题答案大小
      fillBlankQuestions.value.forEach(question => {
        const answer = answers[question.questionId];
        if (answer && typeof answer === 'object') {
          const answerString = JSON.stringify(answer);
          const answerSize = new Blob([answerString]).size;
          totalSize += answerSize;
        }
      });
      
      // 检查单选、多选和判断题答案大小
      const otherAnswers = JSON.stringify(answers);
      totalSize += new Blob([otherAnswers]).size;
      
      console.log(`所有答案总大小: ${totalSize / 1024 / 1024} MB`);
      
      // 如果总大小超过4MB，返回false
      const MAX_SIZE = 4 * 1024 * 1024; // 4MB
      return totalSize <= MAX_SIZE;
    };
    
    // 自动提交确认
    const confirmAutoSubmit = () => {
      if (submitting.value) return;
      
      autoSubmitDialogVisible.value = false;
      // 调用确认提交函数处理提交逻辑
      confirmSubmit();
    };
    
    // 获取分数样式类
    const getScoreClass = (score, totalScore) => {
      if (!score || !totalScore) return 'score-fail';
      
      const percentage = (parseFloat(score) / parseFloat(totalScore)) * 100;
      
      if (percentage >= 90) {
        return 'score-excellent';
      } else if (percentage >= 80) {
        return 'score-good';
      } else if (percentage >= 60) {
        return 'score-pass';
      } else {
        return 'score-fail';
      }
    };
    
    // 格式化填空题学生答案显示
    const formatFillBlankStudentAnswer = (answer) => {
      if (!answer || typeof answer !== 'object') {
        return '(未作答)';
      }
      
      // 检查是否所有空都未填写
      const values = Object.values(answer);
      if (values.length === 0 || values.every(v => !v || v.trim() === '')) {
        return '(未作答)';
      }
      
      // 填空题学生答案是以对象形式存储的，其中键是空的索引，值是填入的内容
      // 按空的索引顺序排序并连接
      const sortedValues = [];
      const keys = Object.keys(answer).sort((a, b) => parseInt(a) - parseInt(b));
      
      for (const key of keys) {
        const value = answer[key];
        if (value && value.trim() !== '') {
          sortedValues.push(value.trim());
        } else {
          sortedValues.push('(空)'); // 标记未填写的空
        }
      }
      
      return sortedValues.join('; ') || '(未作答)';
    };
    
    // 格式化填空题正确答案显示
    const formatFillBlankCorrectAnswer = (options) => {
      if (!options || !Array.isArray(options) || options.length === 0) {
        console.warn('填空题选项不是数组或为空:', options);
        
        try {
          // 尝试查找对应题目的原始答案
          const questionId = fillBlankQuestions.value.find(q => q.options === options)?.questionId;
          if (questionId) {
            // 首先尝试从simulationData中获取
            const simulationDataObj = JSON.parse(localStorage.getItem('simulationExamData') || '{}');
            const originalQuestion = simulationDataObj.fillBlankQuestions?.find(q => q.questionId === questionId);
            
            // 查找该题目是否有选项
            if (originalQuestion && originalQuestion.options && Array.isArray(originalQuestion.options) && originalQuestion.options.length > 0) {
              console.log('从原始数据中获取选项:', originalQuestion.options);
              
              // 从选项中提取答案内容
              const correctAnswers = originalQuestion.options.map(opt => {
                if (!opt || !opt.optionContent) return '';
                return opt.optionContent;
              }).filter(Boolean);
              
              if (correctAnswers.length > 0) {
                console.log('提取的答案内容:', correctAnswers);
                
                // 如果答案内容中有多个可能答案（用|||分隔），将它们转换为"或"的形式
                const formattedAnswers = correctAnswers.map(ans => {
                  if (ans && ans.includes('|||')) {
                    return ans.split('|||').map(a => a.trim()).join(' 或 ');
                  }
                  return ans;
                });
                
                return formattedAnswers.join('; ');
              }
            }
            
            // 如果没有找到选项，尝试直接使用answer字段
            if (originalQuestion && originalQuestion.answer) {
              const answerValue = originalQuestion.answer;
              // 判断answer是否可能是空的数量而不是答案内容
              if (answerValue && /^\d+$/.test(answerValue)) {
                if (parseInt(answerValue) === 1) {
                  return '正确答案请查看题目选项';
                }
                return `该题有${answerValue}个空，正确答案请查看题目选项`;
              }
              return answerValue;
            }
          }
        } catch (e) {
          console.error('尝试从原始数据获取答案时出错:', e);
        }
        
        return '(未找到正确答案)';
      }
      
      console.log('格式化填空题答案，原始选项:', options);
      
      // 填空题正确答案存储在选项中，每个选项对应一个空
      // 处理每个选项的内容，如果有多个正确答案(使用|||分隔)，将其转换为"答案1 或 答案2"的格式
      const formattedAnswers = options.map((option, index) => {
        if (!option || !option.optionContent) {
          console.warn(`选项${index}无内容:`, option);
          return '(无答案)';
        }
        
        let content = option.optionContent;
        // 处理多种正确答案的情况
        if (content && content.includes('|||')) {
          return content.split('|||').map(a => a.trim()).join(' 或 ');
        }
        return content;
      });
      
      console.log('格式化后的填空题答案:', formattedAnswers);
      return formattedAnswers.join('; ') || '(无正确答案)';
    };
    
    // 计算总分
    const calculateTotalScore = () => {
      let totalScoreValue = 0;
      
      // 计算各题型分数
      singleChoiceQuestions.value.forEach(q => {
        totalScoreValue += q.isCorrect ? parseFloat(q.questionScore) : 0;
      });
      
      multiChoiceQuestions.value.forEach(q => {
        totalScoreValue += q.isCorrect ? parseFloat(q.questionScore) : 0;
      });
      
      judgmentQuestions.value.forEach(q => {
        totalScoreValue += q.isCorrect ? parseFloat(q.questionScore) : 0;
      });
      
      fillBlankQuestions.value.forEach(q => {
        // 已在autoGradeExam中计算myScore
        totalScoreValue += parseFloat(q.myScore || 0);
      });
      
      return totalScoreValue;
    };
    
    // 格式化分数为一位小数
    const formatScore = (score) => {
      return parseFloat(score).toFixed(1);
    };
    
    // 格式化得分显示
    const formatDisplayScore = (score, totalScore) => {
      return `${formatScore(score)}/${formatScore(totalScore)}`;
    };

    // 获取题型标题，动态设置题号
    const getSectionTitle = (questionType) => {
      // 定义题型文本
      const typeTexts = ['单选题', '多选题', '判断题', '填空题', '简答题'];
      // 定义中文数字
      const chineseNumbers = ['一', '二', '三', '四', '五'];
      
      // 确定当前题型的索引
      let sectionIndex = 0;
      
      // 计算应该使用的索引
      if (singleChoiceQuestions.value.length > 0 && questionType > 0) sectionIndex++;
      if (multiChoiceQuestions.value.length > 0 && questionType > 1) sectionIndex++;
      if (judgmentQuestions.value.length > 0 && questionType > 2) sectionIndex++;
      if (fillBlankQuestions.value.length > 0 && questionType > 3) sectionIndex++;
      
      // 返回格式化的标题
      return `${chineseNumbers[sectionIndex]}、${typeTexts[questionType]}`;
    };

    // 获取得分显示的CSS类
    const getScoreDisplayClass = (question) => {
      if (question.isCorrect) {
        return 'score-correct';
      } else if (question.myScore && parseFloat(question.myScore) > 0) {
        return 'score-partial'; // 部分得分
      } else {
        return 'score-wrong';
      }
    };
    
    return {
      paper,
      questions,
      allQuestions,
      answers,
      loading,
      submitting,
      saving,
      remainingTime,
      warningTime,
      submitDialogVisible,
      autoSubmitDialogVisible,
      resultDialogVisible,
      singleChoiceQuestions,
      multiChoiceQuestions,
      judgmentQuestions,
      fillBlankQuestions,
      essayQuestions,
      singleChoiceScore,
      multiChoiceScore,
      judgmentScore,
      fillBlankScore,
      essayScore,
      singleChoiceTotal,
      multiChoiceTotal,
      judgmentTotal,
      fillBlankTotal,
      essayTotal,
      fillBlankValues,
      editorOptions,
      formatTime,
      processBlankQuestion,
      submitAnswer,
      confirmSubmit,
      saveProgress,
      confirmAutoSubmit,
      renderMathJax,
      userStore,
      submitTest,
      totalScore,
      getQuestionTypeText,
      formatMyAnswer,
      formatCorrectAnswer,
      timerWarning,
      timeText,
      getScoreClass,
      formatFillBlankStudentAnswer,
      formatFillBlankCorrectAnswer,
      calculateTotalScore,
      formatDisplayScore,
      getSectionTitle,
      getScoreDisplayClass
    };
  }
};
</script>

<style>
/* 全局样式，确保MathJax公式正确显示 */
.app-container .MathJax {
  display: inline-block !important;
  margin: 0 3px;
  vertical-align: middle;
}

.app-container .katex {
  font-size: 1.1em;
}

/* 富文本编辑器样式 */
.ql-editor {
  min-height: 150px;
  font-size: 14px;
}

.ql-toolbar {
  background-color: #f8f8f8;
}

.ql-container {
  background-color: #fff;
}
</style>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.paper-info {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  position: relative;
}

.paper-title {
  text-align: center;
  font-size: 1.5rem;
  margin-bottom: 20px;
}

.paper-metadata {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.metadata-item {
  margin: 0 15px;
  display: flex;
  align-items: center;
}

.score-value {
  font-weight: bold;
  color: #f56c6c;
}

.timer-container {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.timer {
  padding: 8px 16px;
  border-radius: 4px;
  background-color: #ecf5ff;
  color: #409eff;
  display: inline-flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  border: 1px solid #d9ecff;
}

.timer-warning {
  background-color: #fff6f7;
  color: #f56c6c;
  border-color: #fde2e2;
  animation: blink 1s infinite;
}

@keyframes blink {
  50% {
    opacity: 0.7;
  }
}

.time-text {
  margin-left: 8px;
}

.paper-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.question-section {
  margin-bottom: 30px;
}

.section-title {
  padding: 10px;
  background-color: #ecf5ff;
  border-left: 5px solid #409EFF;
  margin-bottom: 20px;
  font-weight: bold;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
  box-sizing: border-box;
}

.error-question {
  border: 2px solid #F56C6C;
  padding: 19px;
}

.question-content {
  margin-bottom: 15px;
}

.question-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.question-index {
  margin-right: 5px;
  font-weight: bold;
}

.question-type {
  margin-right: 10px;
  color: #409EFF;
}

.question-score {
  margin-left: 10px;
  color: #e42e2e;
}


:deep(.blank-input) {
  border: none;
  border-bottom: 1px solid #409eff;
  background-color: #f5f7fa;
  padding: 5px 8px;
  margin: 0 5px;
  min-width: 100px;
  text-align: center;
  outline: none;
  transition: all 0.3s;
}

:deep(.blank-input:focus) {
  border-bottom: 2px solid #409eff;
  background-color: #ecf5ff;
}

.result-summary {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.result-meta {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin-top: 15px;
}

.meta-item {
  margin: 5px 15px;
}

.question-results {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
}

.answer-area {
  border-top: 1px solid #eee;
  padding-top: 15px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

.student-answer, .correct-answer, .score-display {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  align-items: flex-start;
}

.answer-label {
  font-weight: bold;
  margin-bottom: 5px;
  min-width: 90px;
  display: inline-block;
}

.answer-content {
  color: #606266;
  word-break: break-all;
  margin-bottom: 10px;
  flex: 1;
  display: inline-block;
}

.score-label {
  font-weight: bold;
  margin-right: 10px;
  display: inline-block;
}

.score-excellent {
  color: #67C23A;
}

.score-good {
  color: #409EFF;
}

.score-pass {
  color: #E6A23C;
}

.score-fail {
  color: #F56C6C;
}

.paper-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  padding: 20px 0;
}

.paper-footer .el-button {
  min-width: 120px;
}

.answer-textarea {
  white-space: pre-wrap;
}
.options-container {
  margin-left: 20px;
  margin-top: 15px;
}

.option-row {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.option-label {
  font-weight: bold;
  margin-right: 5px;
  min-width: 20px;
}

.option-content {
  white-space: normal;
}
:deep(.el-radio) {
  width: 100%;
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

:deep(.el-checkbox) {
  width: 100%;
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.options-container {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 5px 0;
}

.option-key {
  margin-right: 8px;
  font-weight: bold;
  min-width: 25px;
}

.option-content {
  flex: 1;
  line-height: 1.5;
}

:deep(.el-radio__label),
:deep(.el-checkbox__label) {
  display: flex;
  align-items: flex-start;
  white-space: normal;
  line-height: 1.5;
}

:deep(.el-radio__inner),
:deep(.el-checkbox__inner) {
  margin-top: 3px;
}

:deep(.option-content p) {
  margin: 0;
  display: inline;
}

.score-correct {
  color: #67C23A; /* 绿色 - 正确 */
  font-weight: bold;
}
.score-partial {
  color: #E6A23C; /* 橙色 - 部分正确 */
  font-weight: bold;
}
.score-wrong {
  color: #F56C6C; /* 红色 - 错误 */
  font-weight: bold;
}
</style>

<style>
.question-text img, .option-content img {
  max-width: 100%;
  height: auto;
}

.ql-editor {
  min-height: 100px;
}
</style>

